<?php

namespace App\Common\Util;

use App\Common\Exception\ApiMessageException;
use App\Common\Util\Lock\FileLock;

/**
 * Class Lock
 */
class Lock
{
    /**
     * @param string   $key
     * @param callable $lockCallable
     * @param string   $message
     *
     * @return mixed
     * @throws ApiMessageException
     */
    public static function lock(string $key, callable $lockCallable, string $message = "请稍后再试..."): mixed
    {
        $key = "av-" . $key;

        $lockInstance = TP::config('cache.lock') ?: FileLock::class;

        if (!$lock = $lockInstance::up($key)){
            throw new ApiMessageException($message);
        }

        try {
            $res = call_user_func($lockCallable);
        } finally {
            $lock->down();
        }

        return $res;
    }
}